<?php
namespace App\Api\Controllers\Yinka;


use App\Models\YinkaStore;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
class BaseController
{
    static $config, $instance, $data;

    const TOKEN = '/tran/open/v1/getToken';//'https://ycb.yinkagroup.com/openpay/OpenPayApi/getToken';
    const SCAN_PAY = '/tran/open/v1/scanPay';//'https://ycb.yinkagroup.com/openpay/OpenPayApi/micropay';
    const ORDER_QUERY= '/tran/open/v1/query';//https://ycb.yinkagroup.com/openpay/OpenPayApi/findByorder';
    const REFUND = '/tran/open/v1/refund';
    const REFUND_QUERY = '/tran/open/v1/queryRefund';

    const JS_API_PAY= '/tran/open/v1/jsApi';

    const MIAN = 'https://ycb.yinkagroup.com/ipay-api';


    public static function getInstance ()
    {
        if (! isset(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function params ($data, $priKey)
    {
        self::$data = $data;
        self::$data['sign'] = self::createSign(self::signStr(self::$data), $priKey, 'RSA');
        return $this;
    }

    public static function createSign($data, $priKey)
    {
        $res = "-----BEGIN RSA PRIVATE KEY-----\n" .
            wordwrap($priKey, 64, "\n", true) .
            "\n-----END RSA PRIVATE KEY-----";

        ($res) or die('您使用的私钥格式错误，请检查RSA私钥配置');

        openssl_sign($data, $sign, $res, 'SHA256');

        $sign = base64_encode($sign);
        return $sign;
    }


    public function getToken ($mch)
    {
        $params = [
            'appId' => $mch->account_id,
            'appSecret' =>  $mch->key,
            'sn' => $mch->sn
        ];

        $signStr = self::signStr($params);

        $params['sign'] = self::createSign($signStr, $mch->pri_key);
        $headers[] = 'Content-Type: application/json';
        $headers[] = 'Charset: UTF-8';
        $data = $this->postCurl(self::TOKEN, json_encode($params), $headers);


        if (isset($data['data']['token']) && !empty($data['data']['token'])) {
            $token = $data['data']['token'];
            //存入缓存7200秒
            YinkaStore::where(['store_id' => $mch->store_id])->update(['token' => $token, 'expired_at' => time()+7200]);
            return $token;
        }
    }

    public static function signStr ($params)
    {
        $str = '';
        ksort($params);
        $i = 0;
        foreach($params as $k => $v) {
            if ($v === null || $v == null || $v == '') {
                continue;
            }
            if ($i == 0) {
                $str .= "$k" . "=" . "$v";
            } else {
                $str .= "&" . "$k" . "=" . "$v";
            }
            $i++;
        }
        return $str;
    }

    public function build ($url, $token)
    {
        $headers[]  =  "Authorization:  ". $token;
        $headers[] = 'Content-Type: application/json';
        $headers[] = 'Charset: UTF-8';
        return $this->postCurl($url, json_encode(self::$data), $headers);
    }

    public function postCurl ($url, $data, $headers)
    {
        $curl = curl_init();
        if ($headers) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }
        curl_setopt($curl, CURLOPT_URL, self::MIAN.$url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

        $tmpInfo = curl_exec($curl);     //返回api的json对象
        $a = curl_error($curl);
        if(!empty($a)){
            error_log(date('Y-m-d H:i:s')." 【银卡error】： ".json_encode([$a])."\n\n", 3, "/tmp/". 'yinka'.date('Ymd').".log");
        }
        curl_close($curl);
        error_log(date('Y-m-d H:i:s')." 【银卡】： ".json_encode([$url,$data,$tmpInfo])."\n\n", 3, "/tmp/". 'yinka'.date('Ymd').".log");

        return json_decode($tmpInfo, true);
    }


}